package com.hfqixin.api.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.hfqixin.assess.bean.OutputHome1;
import com.hfqixin.equipment.bean.CheckItem;
import com.hfqixin.equipment.bean.Equipment;
import com.hfqixin.equipment.bean.OutputEquipment;
import com.hfqixin.equipment.bean.OutputHome;
import com.hfqixin.equipment.service.CheckItemService;
import com.hfqixin.equipment.service.EquipmentService;
import com.hfqixin.ipqc.bean.IPQC;
import com.hfqixin.ipqc.service.IPQCService;
import com.hfqixin.manager.bean.DataAuthority;
import com.hfqixin.manager.controller.BaseController;
import com.hfqixin.manager.util.DateUtil;
import com.hfqixin.manager.util.SessionUtils;
import com.hfqixin.record.bean.CheckImage;
import com.hfqixin.record.bean.CheckRecord;
import com.hfqixin.record.bean.OutputHistory;
import com.hfqixin.record.service.CheckImageService;
import com.hfqixin.record.service.CheckRecordService;

@Controller
@RequestMapping(value = "check/api")
public class ControllerApi2 extends BaseController {

	@Autowired
	private EquipmentService equipmentService;

	@Autowired
	private CheckItemService itemService;

	@Autowired
	private IPQCService ipqcService;

	@Autowired
	private CheckImageService imageService;

	@Autowired
	private CheckRecordService recordService;

	// 登陆接口
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public void postLogin(HttpServletRequest request, HttpServletResponse response, @RequestBody IPQC ipqc) {
		@SuppressWarnings("unused")
		DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
		try {
			IPQC ipqc1 = ipqcService.checkUserLogin(ipqc);
			if (ipqc1 == null) {
				respErrorMsg(response, "登录失败，请检查帐号和密码");
			} else {
				String staffId = ipqc1.getId();
				// 写数据到session，并跳转到主页
				// 跳转主页是通过异步请求的方式完成
				SessionUtils.setAttr(request, "staffIdInfo", staffId);
				SessionUtils.setAttr(request, "staffInfo", ipqc1);
				// 继承父类BaseController的方法
				respSuccessMsg(response, ipqc1, "登录成功");
			}
		} catch (Exception e) {
			respErrorMsg(response, "登录异常，请联系网站管理员");
		}
	}

	
	@RequestMapping(value = "/checkHome", method = RequestMethod.POST)
	public void checkHome(HttpServletRequest request, HttpServletResponse response,@RequestBody IPQC ipqc){
		@SuppressWarnings("unused")
		DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
		List<OutputHome> homeList = new ArrayList<>();
		OutputHome1 home1 =  new OutputHome1();
		Date currentTime = new Date();
		String currTime = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
		Date endTime;
		try {
			List<Equipment> list = equipmentService.getEquipmentList(ipqc);
			int x = 0,p = 0,t = 0 ;
			if(list != null && list.size() > 0){
				for(int i = 0 ; i < list.size() ; i++){
					list.get(i).setStartTime2(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
					list.get(i).setEndTime2(new SimpleDateFormat("yyyy-MM-dd").format(new Date())+" 23:59:59");
					List<CheckItem> itemList = itemService.getCheckItemList2(list.get(i));
					CheckItem item = new CheckItem();
					OutputHome output = new OutputHome();
					for (int k = 0; k < itemList.size(); k++) {
						if (itemList.get(k).getCheckTime() == null) {
							itemList.get(k).setCheckTime(DateUtil.getDate(new Date(), -1));
						}
						endTime = DateUtil.getDate(itemList.get(k).getCheckTime(), itemList.get(k).getFrequency());
						String endTime1 = new SimpleDateFormat("yyyy-MM-dd").format(endTime);

						if (endTime1.compareTo(currTime) > 0) {
							item.setId(itemList.get(k).getId());
							item.setStatus(0);
							item.setRemark(
									"还有" + ((endTime.getTime() - currentTime.getTime()) / 1000 / 60 / 60 / 24 ) + "天");
							item.setDeadLine(endTime);
							itemService.updateCheckItem(item);
						}

						if (endTime1.compareTo(currTime) == 0) {
							item.setId(itemList.get(k).getId());
							item.setStatus(1);
							item.setRemark("今天需检");
							item.setDeadLine(endTime);
							itemService.updateCheckItem(item);
							p++;
						}

						if (endTime1.compareTo(currTime) < 0) {
							item.setId(itemList.get(k).getId());
							item.setStatus(2);
							item.setRemark(
									"过期" + ((currentTime.getTime() - endTime.getTime()) / 1000 / 60 / 60 / 24) + "天");
							item.setDeadLine(endTime);
							itemService.updateCheckItem(item);
							x++;
						}
						
					}
					itemList = itemService.getCheckItemList3(list.get(i));
					
					for(int a = 0 ; a < itemList.size() ; a++){
						String temDateStr = "";
						if(itemList.get(a).getCheckTime() == null){
							temDateStr = "1980-1-1";
						}else{
							temDateStr =new SimpleDateFormat("yyyy-MM-dd").format(itemList.get(a).getCheckTime());  
						}
						
						if(currTime.compareTo(temDateStr) == 0){
							itemList.get(a).setCheckToday(true);
							t++;
						}else{
							itemList.get(a).setCheckToday(false);
						}
					}
					output.setId(list.get(i).getId());
					output.setEquipmentName(list.get(i).getName());
					output.setTotal(itemList.size());
					output.setCheckedItem(t);
					homeList.add(output);
				}
				System.err.println(p);
				home1.setCheckTodayTotol(p+x);
				home1.setOverdueTotal(x);
				home1.setHomeList(homeList);
				respSuccessMsg(response, home1, "查询成功");
			}else{
				respSuccessMsg(response, null, "该巡检员没有检查的设备");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			respErrorMsg(response, "系统异常");
		}
	}
	
	@RequestMapping(value = "/showCheckItem", method = RequestMethod.POST)
	public void showCheckItem(HttpServletRequest request, HttpServletResponse response, @RequestBody Equipment equipment){
		@SuppressWarnings("unused")
		DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
		Date currentTime = new Date();
		String currTime = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
		try {
			Equipment equipment1 = equipmentService.getEquipment(equipment.getId());
			List<CheckItem> itemList = itemService.getCheckItemList4(equipment);
			OutputHome home = new OutputHome();
			if(itemList != null && itemList.size() > 0){
				for(int a = 0 ; a < itemList.size() ; a++){
					String temDateStr = "";
					if(itemList.get(a).getCheckTime() == null){
						temDateStr = "1980-1-1";
					}else{
						temDateStr =new SimpleDateFormat("yyyy-MM-dd").format(itemList.get(a).getCheckTime());  
					}
					if(currTime.compareTo(temDateStr) == 0){
						itemList.get(a).setCheckToday(true);
					}else{
						itemList.get(a).setCheckToday(false);
					}
				}
			}
			if(null != equipment1){
				home.setId(equipment1.getId());
				home.setEquipmentName(equipment1.getName());
				home.setSite(equipment1.getSite());
			}
			
			home.setItemList(itemList);
			CheckRecord record = new CheckRecord();
			record.setStartTime(DateUtil.lastDay(currentTime)[0]);
			record.setEndTime(DateUtil.lastDay(currentTime)[0] + " 23:59:59");
			Integer temp = recordService.countDisqualification(record);
			home.setDisqualification(temp);
			respSuccessMsg(response, home, "查询成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			respErrorMsg(response, "系统异常");
		}
	}
	
	// 原主页(暂时不用)
	@RequestMapping(value = "/home", method = RequestMethod.POST)
	public void home(HttpServletRequest request, HttpServletResponse response, @RequestBody IPQC ipqc) {
		@SuppressWarnings("unused")
		DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
		Date currentTime = new Date();
		String currTime = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
		Date endTime;
		try {
			List<CheckItem> list = itemService.getCheckItemList1(ipqc);
			CheckItem item = new CheckItem();
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getCheckTime() == null) {
					list.get(i).setCheckTime(new Date());
				}
				endTime = DateUtil.getDate(list.get(i).getCheckTime(), list.get(i).getFrequency());
				String endTime1 = new SimpleDateFormat("yyyy-MM-dd").format(endTime);

				if (endTime1.compareTo(currTime) > 0) {
					item.setId(list.get(i).getId());
					item.setStatus(0);
					item.setRemark(
							"还有" + ((endTime.getTime() - currentTime.getTime()) / 1000 / 60 / 60 / 24 + 1) + "天");
					item.setDeadLine(endTime);
					itemService.updateCheckItem(item);
				}

				if (endTime1.compareTo(currTime) == 0) {
					item.setId(list.get(i).getId());
					item.setStatus(1);
					item.setRemark("今天需检");
					item.setDeadLine(endTime);
					itemService.updateCheckItem(item);
				}

				if (endTime1.compareTo(currTime) < 0) {
					item.setId(list.get(i).getId());
					item.setStatus(2);
					item.setRemark(
							"过期" + ((currentTime.getTime() - endTime.getTime()) / 1000 / 60 / 60 / 24 + 1) + "天");
					item.setDeadLine(endTime);
					itemService.updateCheckItem(item);
				}

			}
			ipqc.setStartTime1(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
			Date temTime = DateUtil.getDate(new Date(), 5);
			ipqc.setEndTime1(new SimpleDateFormat("yyyy-MM-dd").format(temTime) + " 23:59:59");
			List<CheckItem> list1 = itemService.getCheckItemList(ipqc);
			respSuccessMsg(response, list1, "查询成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			respErrorMsg(response, "系统异常");
		}
	}

	/*// 巡检回显
	@RequestMapping(value = "/getCheckItem", method = RequestMethod.POST)
	public void getCheckItem(HttpServletRequest request, HttpServletResponse response, @RequestBody CheckItem item) {
		@SuppressWarnings("unused")
		DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
		try {
			CheckItem item1 = itemService.getCheckItem(item.getId());
			respSuccessMsg(response, item1, "查询成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			respErrorMsg(response, "系统异常");
		}
	}*/
	
	// 巡检回显
		@RequestMapping(value = "/getCheckItem", method = RequestMethod.POST)
		public void getCheckItem(HttpServletRequest request, HttpServletResponse response, @RequestBody CheckItem item) {
			@SuppressWarnings("unused")
			DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
			try {
				CheckItem item1 = itemService.getCheckItem(item.getId());
				CheckRecord record = recordService.getCheckPlan(item);
				if(record == null){
					record = new CheckRecord();
					record.setItemId(item.getId());
					record.setCheckPoint("暂无检查重点");
					record.setStatus(1);
					record.setItemName(item1.getName());
					record.setEquipmentId(item1.getEquipmentId());
					record.setEquipmentName(item1.getEquipmentName());
					record.setFrequency(item1.getFrequency());
					record.setContent(item1.getContent());
					recordService.insertCheckRecord(record);
					record = recordService.getCheckPlan(item);
				}
				record.setDeadLine(new SimpleDateFormat("yyyy-MM-dd").format(item1.getDeadLine()));
				respSuccessMsg(response, record, "查询成功");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				respErrorMsg(response, "系统异常");
			}
		}
		
		
	//修改时巡检回显	
		@RequestMapping(value = "/getCheckResult", method = RequestMethod.POST)
		public void getCheckResult(HttpServletRequest request, HttpServletResponse response, @RequestBody CheckItem item) {
			@SuppressWarnings("unused")
			DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
			try {
				CheckItem item1 = itemService.getCheckItem(item.getId());
				CheckRecord record = recordService.showCheckRecord(item.getId());
				if(record == null ){
					record = new CheckRecord();
				}
				record.setDeadLine(new SimpleDateFormat("yyyy-MM-dd").format(item1.getDeadLine()));
				respSuccessMsg(response, record, "查询成功");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				respErrorMsg(response, "系统异常");
			}
		}
	
/*
	// 提交检查结果
	@RequestMapping(value = "/check", method = RequestMethod.POST)
	public void check(HttpServletRequest request, HttpServletResponse response, @RequestBody CheckRecord record) {
		@SuppressWarnings("unused")
		DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
		CheckItem item = new CheckItem();
		try {
			CheckItem item2 = itemService.getCheckItem(record.getItemId());
			if (item2 != null) {
				record.setItemName(item2.getName());
				record.setEquipmentId(item2.getEquipmentId());
				record.setEquipmentName(item2.getEquipmentName());
				record.setIpqcId(item2.getIqpcId());
				record.setIpqcName(item2.getIqpcName());
			}
			recordService.insertCheckRecord(record);
			item.setId(record.getItemId());
			item.setCheckPoint(record.getCheckPoint());
			item.setCheckTime(new Date());
			item.setNextCheckTime(record.getCheckTime());
			itemService.updateCheckItem(item);
			respSuccessMsg(response, record, "检查成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			respErrorMsg(response, "检查失败");
		}
	}*/
	
	
	
	// 提交检查结果
		@RequestMapping(value = "/check", method = RequestMethod.POST)
		public void check(HttpServletRequest request, HttpServletResponse response, @RequestBody CheckRecord record) {
			@SuppressWarnings("unused")
			DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
			CheckItem item = new CheckItem();
			try {
				CheckItem item2 = itemService.getCheckItem(record.getItemId());
				IPQC ipqc = ipqcService.getIPQC(record.getIpqcId());
				CheckRecord plan = recordService.getCheckPlan(item2);				
				if (item2 != null) {
					record.setItemName(item2.getName());
					record.setEquipmentId(item2.getEquipmentId());
					record.setEquipmentName(item2.getEquipmentName());
					record.setIpqcId(record.getIpqcId());
					record.setIpqcName(ipqc.getName());
					record.setFrequency(item2.getFrequency());
					record.setContent(item2.getContent());
				}
				record.setId(plan.getId());
				record.setStatus(0);
				
				recordService.updateCheckRecord(record);
				
				CheckRecord plan1 = new CheckRecord();
				plan1.setItemId(record.getItemId());
				plan1.setCheckPoint(record.getCheckPoint());
				plan1.setStatus(1);
				plan1.setCheckTime(record.getCheckTime());
				plan1.setItemName(record.getItemName());
				plan1.setIpqcId(record.getIpqcId());
				plan1.setIpqcName(record.getIpqcName());
				plan1.setFrequency(record.getFrequency());
				plan1.setContent(record.getContent());
				recordService.insertCheckRecord(plan1);
				item.setId(record.getItemId());
				item.setCheckPoint(record.getCheckPoint());
				item.setCheckTime(new Date());
				item.setNextCheckTime(record.getCheckTime());
				item.setStatus(4);
				itemService.updateCheckItem(item);
				respSuccessMsg(response, record, "检查成功");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				respErrorMsg(response, "检查失败");
			}
		}
	

	// 我的
	@RequestMapping(value = "/mine", method = RequestMethod.POST)
	public void mine(HttpServletRequest request, HttpServletResponse response, @RequestBody IPQC ipqc) {
		@SuppressWarnings("unused")
		DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
		try {
			List<Equipment> list = equipmentService.getEquipmentList(ipqc);
			respSuccessMsg(response, list, "查询成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			respErrorMsg(response, "查询失败");
		}
	}

	// 我的设备
	@RequestMapping(value = "/lookEquipment", method = RequestMethod.POST)
	public void lookEquipment(HttpServletRequest request, HttpServletResponse response,
			@RequestBody Equipment equipment) {
		@SuppressWarnings("unused")
		DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
		OutputEquipment output = new OutputEquipment();
		try {
			Equipment equipment1 = equipmentService.getEquipment(equipment.getId());
			List<CheckItem> list = itemService.getCheckItemList2(equipment);
			output.setEquipment(equipment1);
			output.setItem(list);
			respSuccessMsg(response, output, "查询成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			respErrorMsg(response, "查询失败");
		}

	}

	// 查看检查项的检查记录
	@RequestMapping(value = "/lookCheckRecord", method = RequestMethod.POST)
	public void lookCheckRecord(HttpServletRequest request, HttpServletResponse response, @RequestBody CheckItem item) {
		@SuppressWarnings("unused")
		DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
		try {
			List<CheckRecord> list = recordService.getCheckRecordList(item);
			List<CheckImage> imageList = new ArrayList<CheckImage>();
			List<OutputHistory> historyList = new ArrayList<OutputHistory>();
			for (int k = 0; k < list.size(); k++) {
				OutputHistory history = new OutputHistory();
				history.setResult(list.get(k).getResult());
				history.setCheckTime(list.get(k).getCheckTime());
				history.setContent(list.get(k).getContent());
				history.setRemark(list.get(k).getRemark());
				history.setEquipmentName(list.get(k).getEquipmentName());
				history.setItemName(list.get(k).getItemName());
				history.setCheckSite(list.get(k).getCheckSite());
				imageList = imageService.getCheckImageList(list.get(k));
				if(imageList != null){
					history.setImageList(imageList);
					historyList.add(history);
				}
				System.err.println(history);
				
			}
			respSuccessMsg(response, historyList, "查询成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			respErrorMsg(response, "查询失败");
		}
	}

	// 历史记录
	@RequestMapping(value = "/historyRecord", method = RequestMethod.POST)
	public void historyRecord(HttpServletRequest request, HttpServletResponse response, @RequestBody IPQC ipqc) {
		@SuppressWarnings("unused")
		DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
		try {

			List<CheckRecord> list = recordService.getCheckRecordList1(ipqc);
			List<CheckImage> imageList = new ArrayList<CheckImage>();
			List<OutputHistory> historyList = new ArrayList<OutputHistory>();
		
			for (int k = 0; k < list.size(); k++) {
				OutputHistory history = new OutputHistory();
				history.setResult(list.get(k).getResult());
				history.setCheckTime(list.get(k).getCheckTime());
				history.setContent(list.get(k).getContent());
				history.setRemark(list.get(k).getRemark());
				history.setEquipmentName(list.get(k).getEquipmentName());
				history.setItemName(list.get(k).getItemName());
				history.setCheckSite(list.get(k).getCheckSite());
				imageList = imageService.getCheckImageList(list.get(k));
				if(imageList != null){
					history.setImageList(imageList);
					historyList.add(history);
				}
				System.err.println(history);
				
			}
			respSuccessMsg(response, historyList, "查询成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			respErrorMsg(response, "查询失败");
		}
	}

	@RequestMapping("image")
	public void imageUpload(HttpServletResponse response, HttpServletRequest request) {
		@SuppressWarnings("unused")
		DataAuthority dataAuthority = SessionUtils.getCurrDataAuthority(request);
		MultipartFile file = null;
		System.err.println("图片上传");
		if (request instanceof MultipartHttpServletRequest) {
			Collection<MultipartFile> files = ((MultipartHttpServletRequest) request).getFileMap().values();
			if (files != null && !files.isEmpty()) {
				file = new ArrayList<MultipartFile>(files).get(0);
			} else {
				respErrorMsg(response, "请至少选择一个文件");
				return;
			}
		} else {
			respErrorMsg(response, "请至少选择一个文件");
			return;
		}

		try {
			if (file.isEmpty()) {
				respErrorMsg(response, "请至少选择一个文件");
				return;
			} else {

				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
				String res = sdf.format(new Date());

				// uploads文件夹位置
				String rootPath = request.getSession().getServletContext().getRealPath("uploads/");
				// 原始名称
				String originalFileName = file.getOriginalFilename();

				// 新文件名
				String newFileName = "hfqixin" + res + originalFileName.substring(originalFileName.lastIndexOf("."));
				/*
				 * String fileExtName =
				 * tempFileName.substring(tempFileName.lastIndexOf(".") +
				 * 1).toLowerCase(); //获取文件后缀
				 */ // 创建年月文件夹
				Calendar date = Calendar.getInstance();
				File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));
				Iterator<?> iter = multiRequest.getFileNames();
				System.err.println(rootPath);
				while (iter.hasNext()) {
					// 一次遍历所有文件
					file = multiRequest.getFile(iter.next().toString());
					if (file != null) {
						System.err.println("11");
						// 新文件
						File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
						// 判断目标文件所在目录是否存在
						if (!newFile.getParentFile().exists()) {
							// 如果目标文件所在的目录不存在，则创建父目录
							newFile.getParentFile().mkdirs();
						}
						System.out.println(newFile);
						// 将内存中的数据写入磁盘
						file.transferTo(newFile);
						String requestUrl = request.getScheme() // 当前链接使用的协议
								+ "://" + request.getServerName()// 服务器地址
								+ ":" + request.getServerPort() // 端口号
								+ request.getContextPath(); // 应用名称，如果应用名称为
						// 完整的url
						String path = requestUrl + "/uploads/" + date.get(Calendar.YEAR) + "/"
								+ (date.get(Calendar.MONTH) + 1) + "/" + newFileName;
						System.err.println(path);

						CheckImage image = new CheckImage();
						System.err.println(request.getParameter("rId"));
						image.setrId(request.getParameter("rId"));
						image.setPicUrl(path);
						imageService.insertCheckImage(image);
						System.err.println(requestUrl);
						respSuccessMsg(response, path, "上传成功");
					}

				}

			}
		} catch (Exception e) {
			respErrorMsg(response, "请至少选择一个文件");
			return;
		}
	}

}
